package com.gx.auth.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gx.auth.dao.UserRoleInterfaceDAO;
import com.gx.auth.entity.UserRole;


public class UserRoleInterfaceImplDAO implements UserRoleInterfaceDAO{
	private  Connection conn = null;
	
	
	public UserRoleInterfaceImplDAO(Connection conn) {
		this.conn = conn;
	}
	
	
	
	@Override
	public int insert(UserRole t) throws SQLException {
		String sql = "insert into auth_user_role (r_id,u_id,status,createtime,updatetime) values (?,?,?,datetime('now', 'localtime'),datetime('now', 'localtime')) "  ;
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setInt(1, t.getRid());
		pst.setInt(2, t.getUid());
		pst.setBoolean(3, t.getStatus());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	
	@Override
	public int delete(UserRole t) throws SQLException {
		String sql = "delete from auth_user_role where u_id = ?  "  ;
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setInt(1, t.getUid());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public int update(UserRole t) throws SQLException {
		String sql = "update auth_user_role set status = ?,updatetime = datetime('now', 'localtime') where  u_id =? "  ;
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setBoolean(1, t.getStatus());
		pst.setInt(2, t.getUid());
		int count = pst.executeUpdate();
		pst.close();
		return count;
	}

	@Override
	public UserRole query(int uid) throws SQLException {
		UserRole ur = new UserRole();
		String sql = "select * from auth_user_role where u_id = ?  ";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setInt(1, uid);
		ResultSet rs = pst.executeQuery();
		if(rs.next()) {
			ur = saveResult(rs);
		}
		rs.close();
		pst.close();
		return ur;
	}

	@Override
	public List<UserRole> queryAll() throws SQLException {
		List<UserRole> ls = new ArrayList<>();
		String sql = "select * from auth_user_role ";
		PreparedStatement pst = conn.prepareStatement(sql);
		ResultSet rs = pst.executeQuery();
		while(rs.next()) {
			ls.add(saveResult(rs));
		}
		rs.close();
		pst.close();
		return ls;
	}



	@Override
	public UserRole saveResult(ResultSet rs) throws SQLException {
		UserRole ur = new UserRole();
		ur.setRid(rs.getInt("r_id"));
		ur.setUid(rs.getInt("r_id"));
		ur.setUrid(rs.getInt("ur_id"));
		ur.setStatus(rs.getBoolean("status"));
		ur.setCreatetime(rs.getString("createtime"));
		ur.setUpdatetime(rs.getString("updatetime"));
		return ur;
	}

}
